package com.uniflow.controller;

import com.uniflow.common.PageResult;
import com.uniflow.common.Result;
import com.uniflow.entity.TaskCenter;
import com.uniflow.service.TaskCenterService;
import com.uniflow.service.WorkflowService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 候选人任务测试控制器
 * 用于演示BPMN动态候选人绑定功能
 */
@Api(tags = "候选人任务测试")
@RestController
@RequestMapping("/api/v1/test/candidate-tasks")
public class CandidateTaskTestController {
    
    @Autowired
    private WorkflowService workflowService;
    
    @Autowired
    private TaskCenterService taskCenterService;
    
    /**
     * 启动候选人任务流程
     */
    @ApiOperation("启动候选人任务流程")
    @PostMapping("/start-process")
    public Result<Map<String, Object>> startCandidateTaskProcess(
            @ApiParam("业务键") @RequestParam String businessKey,
            @ApiParam("启动用户ID") @RequestParam String startUserId) {
        
        try {
            // 准备流程变量
            Map<String, Object> variables = new HashMap<>();
            variables.put("startUserId", startUserId);
            variables.put("businessKey", businessKey);
            
            // 启动流程
            String processInstanceId = workflowService.startProcessInstance(
                "candidateTaskProcess", businessKey, variables, startUserId);
            
            // 返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("processInstanceId", processInstanceId);
            result.put("businessKey", businessKey);
            result.put("message", "候选人任务流程启动成功");
            
            return Result.success(result);
            
        } catch (Exception e) {
            return Result.error("启动流程失败: " + e.getMessage());
        }
    }
    
    /**
     * 查询流程中的候选任务
     */
    @ApiOperation("查询流程中的候选任务")
    @GetMapping("/process-tasks/{processInstanceId}")
    public Result<List<TaskCenter>> getProcessCandidateTasks(
            @ApiParam("流程实例ID") @PathVariable String processInstanceId) {
        
        try {
            List<TaskCenter> tasks = taskCenterService.getTasksByProcessInstanceId(processInstanceId);
            return Result.success(tasks);
            
        } catch (Exception e) {
            return Result.error("查询任务失败: " + e.getMessage());
        }
    }
    
    /**
     * 认领候选任务
     */
    @ApiOperation("认领候选任务")
    @PostMapping("/claim-task")
    public Result<String> claimTask(
            @ApiParam("任务ID") @RequestParam String taskId,
            @ApiParam("认领用户ID") @RequestParam String userId,
            @ApiParam("认领用户名") @RequestParam(required = false) String userName) {
        
        try {
            if (userName == null || userName.trim().isEmpty()) {
                userName = "测试用户";
            }
            taskCenterService.claimTask(taskId, userId, userName);
            return Result.success("任务认领成功");
            
        } catch (Exception e) {
            return Result.error("认领任务失败: " + e.getMessage());
        }
    }
    
    /**
     * 完成任务
     */
    @ApiOperation("完成任务")
    @PostMapping("/complete-task")
    public Result<String> completeTask(
            @ApiParam("任务ID") @RequestParam String taskId,
            @ApiParam("执行用户ID") @RequestParam String userId,
            @ApiParam("执行用户名") @RequestParam(required = false) String userName) {
        
        try {
            if (userName == null || userName.trim().isEmpty()) {
                userName = "测试用户";
            }
            
            taskCenterService.completeTask(taskId, userId, userName);
            return Result.success("任务完成成功");
            
        } catch (Exception e) {
            return Result.error("完成任务失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取用户的候选任务列表（测试用）
     */
    @ApiOperation("获取用户的候选任务列表")
    @GetMapping("/user-candidate-tasks")
    public Result<List<TaskCenter>> getUserCandidateTasks(
            @ApiParam("用户ID") @RequestParam String userId) {
        
        try {
            // 使用候选任务查询功能
            PageResult<TaskCenter> result = taskCenterService.getCandidateTasks(1, 20, userId, null, null, null);
            return Result.success(result.getList());
            
        } catch (Exception e) {
            return Result.error("查询候选任务失败: " + e.getMessage());
        }
    }
    
    /**
     * 部署测试流程
     */
    @ApiOperation("部署测试流程")
    @PostMapping("/deploy-test-process")
    public Result<String> deployTestProcess() {
        
        try {
            String deploymentId = workflowService.deployProcessFromClasspath(
                "processes/candidate-task-process.bpmn", "候选人任务测试流程");
            
            return Result.success("流程部署成功，部署ID: " + deploymentId);
            
        } catch (Exception e) {
            return Result.error("部署流程失败: " + e.getMessage());
        }
    }
}